using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Drawing;

namespace Admaco.Data
{
    /// <summary>
    /// Utilidad de conversion de imagenes a bytes y viceversa
    /// </summary>
    class ConvertirImage
    {
        /// <summary>
        /// Obtiene la secuencia de bytes de una imagen
        /// </summary>
        /// <param name="imagen">Imagen a obtener bytes</param>
        /// <returns>Secuencia de bytes de la imagen</returns>
        public static byte[] getBytes(Image imagen){

            byte[] bytes;

            using (FileStream fs = new FileStream(Path.GetTempFileName(), FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                imagen.Save(fs, System.Drawing.Imaging.ImageFormat.Jpeg);
                fs.Position = 0;
                int imgLength = Convert.ToInt32(fs.Length);
                bytes = new byte[imgLength];
                fs.Read(bytes, 0, imgLength);
            }

            return bytes;
        }

        /// <summary>
        /// Obtiene
        /// </summary>
        /// <param name="bytes">secuencia de bytes</param>
        /// <returns>Imagen a partir de la secuencia de bytes</returns>
        public static Image getImage(byte[] bytes)
        {
            if (bytes == null)
            {
                return null;
            }
            else
            {
                MemoryStream ms = new MemoryStream(bytes);
                Bitmap bm = null;
                try
                {
                    bm = new Bitmap(ms);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                    throw ex;
                }
                return bm;
            }

        }
    }
}
